package com.monitor.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.monitor.entity.*;
import com.monitor.service.*;
import com.monitor.util.IDUtils;
import com.monitor.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 物料流转表 前端控制器
 * </p>
 *
 * @author LX
 * @since 2018-09-08
 */
@RestController
@RequestMapping("/erpMaterielFlow")
@Api(description="物料流转")
public class ErpMaterielFlowController {

    @Resource
    private ErpMaterielFlowService materielFlowService;
    @Resource
    private ErpMaterielService materielService;
    @Resource
    private ErpCustomerService customerService;
    @Resource
    private ErpCustomerWarehouseService customerWarehouseService;
    @Resource
    private ErpWarehouseService warehouseService;
    @Resource
    private ErpMaterielFlowMaterielDetailsService detailsService;
    @Resource
    private ErpMaterielFlowMaterielService flowMaterielService;
    @Resource
    private ErpMaterielFlowSummaryService flowSummaryService;

    @Resource
    private  ErpModelService erpModelService;
    @Resource
    private  ErpSpecificationsService erpSpecificationsService;
    @RequestMapping("/inertOrUpdateMaterielFlow")//ErpMaterielFlowMateriel
    @ApiOperation("物料流转信息添加（出库！！！）")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "gocustId", value = "入库方得客户id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "materielFlowMateriels", value = "List<ErpMaterielFlowMateriel>", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "materielFlow", value = "ErpMaterielFlow", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "当前客户ID", required = false, dataType = "int", paramType = "query")
    })
    //物料流转表存储流转信息  物料表存储流转的物料信息
    public @ResponseBody
    Result<ErpMaterielFlow> inertOrUpdateMaterielFlow(String json) {
        //ErpMaterielFlow materielFlow, List<ErpMateriel> erpMateriels,Integer custId,Integer gocustId
        Result<ErpMaterielFlow> result=new Result<ErpMaterielFlow>();
        try{
            JSONObject jsonObject = JSON.parseObject(json);
            ErpMaterielFlow materielFlow = JSON.parseObject(json, ErpMaterielFlow.class);
            List<ErpMateriel> erpMateriels = materielFlow.getErpMateriels();
            Integer custId = materielFlow.getCustId();
            Integer gocustId = materielFlow.getGocustId();
            ErpCustomer customer=customerService.selectById(custId);//出库客户信息
            ErpCustomer goCustomer=customerService.selectById(gocustId);//入库客户信息
            ErpCustomerWarehouse customerWarehouse=customerWarehouseService.selectOne(new EntityWrapper<ErpCustomerWarehouse>().eq("customer_id",custId));//出库客户仓库
            ErpCustomerWarehouse goCustomerWarehouse=customerWarehouseService.selectOne(new EntityWrapper<ErpCustomerWarehouse>().eq("customer_id",goCustomer.getId()));//入库客户仓库

            //添加物料流转表信息
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-mm-dd");
            String format = simpleDateFormat.format(new Date());
            materielFlow.setMaterielFlowDate(format);

            //查到订单最后一个并截取字符串然后五位然后在添加的时候+1

            List<ErpMaterielFlow> erpMaterielFlows = materielFlowService.selectList(new EntityWrapper<ErpMaterielFlow>());
            String substring = erpMaterielFlows.get(erpMaterielFlows.size() - 1).getMaterielFlowSheetId().substring(erpMaterielFlows.get(erpMaterielFlows.size() - 1).getMaterielFlowSheetId().length() - 5);
            materielFlow.setMaterielFlowSheetId("WLLZ"+IDUtils.genOrderId()+IDUtils.addOne(substring));

            materielFlow.setSourceWarehouseId(customerWarehouse.getId());
            materielFlow.setSourceWarehouseName(customerWarehouse.getWarName());
            materielFlow.setWarehouseId(goCustomerWarehouse.getId());
            materielFlow.setWarehouseName(goCustomerWarehouse.getWarName());
            materielFlow.setFlowDirection(1);//1出库
            materielFlow.setTheId(custId);
            materielFlowService.insertOrUpdate(materielFlow);
            //1添加流转的物料得属性信息          2 计算出库
            for (int i = 0; i <erpMateriels.size() ; i++) {
                //1添加流转的物料得属性信息
                ErpMateriel materiel=erpMateriels.get(i);
                materiel.setMaterielFlowId(materielFlow.getId());
                materielService.insertOrUpdate(erpMateriels.get(i));

                //先查询物料属性信息
                ErpMaterielFlowMateriel materielFlowMateriel=flowMaterielService.selectOne(new EntityWrapper<ErpMaterielFlowMateriel>().eq("materiel_name",erpMateriels.get(i).getMaterielFlowMateriel().getMaterielName()).eq("materiel_brand",erpMateriels.get(i).getMaterielFlowMateriel().getMaterielBrand()).eq("materiel_Specifications",erpMateriels.get(i).getMaterielFlowMateriel().getMaterielSpecifications()).eq("materiel_model",erpMateriels.get(i).getMaterielFlowMateriel().getMaterielModel()).eq("materiel_place",erpMateriels.get(i).getMaterielFlowMateriel().getMaterielPlace()).eq("materiel_state",erpMateriels.get(i).getMaterielFlowMateriel().getMaterielState()).eq("materiel_unit",erpMateriels.get(i).getMaterielFlowMateriel().getMaterielUnit()));
                //2 计算出库
                //*******物料出库**********//*
                ErpWarehouse warehouse=warehouseService.selectOne(new EntityWrapper<ErpWarehouse>().eq("warehouse_id",customerWarehouse.getId()).eq("customer_id",customer.getId()).eq("materiel_id",materielFlowMateriel.getId()));
                Integer num=warehouse.getMaterielNumber();
                warehouse.setMaterielNumber(num-erpMateriels.get(i).getMaterielNumber());
                warehouseService.updateById(warehouse);//修改仓库物料数量
                Integer materielRetained=0;
                if("零星客户".equals(goCustomer.getCusName())){
                    //*****物料入库**********//*
                    ErpWarehouse goWarehouse=warehouseService.selectOne(new EntityWrapper<ErpWarehouse>().eq("warehouse_id",goCustomerWarehouse.getId()).eq("customer_id",goCustomer.getId()).eq("materiel_id",materielFlowMateriel.getId()));

                    if(null==goWarehouse){
                        goWarehouse.setCustomerId(goCustomer.getId());
                        goWarehouse.setWarehouseId(goCustomerWarehouse.getId());
                        goWarehouse.setMaterielId(materielFlowMateriel.getId());
                        warehouseService.insert(goWarehouse);
                    }
                    materielRetained=goWarehouse.getMaterielNumber();
                    goWarehouse.setMaterielNumber(goWarehouse.getMaterielNumber()+erpMateriels.get(i).getMaterielNumber());
                    warehouseService.updateById(goWarehouse);
                }

                //添加物料流转物料详情
                ErpMaterielFlowMaterielDetails materielFlowMaterielDetails=new ErpMaterielFlowMaterielDetails();
                materielFlowMaterielDetails.setMaterielId(materiel.getId());
                materielFlowMaterielDetails.setPid(materielFlow.getId());
                materielFlowMaterielDetails.setMaterielStudy(0);
                detailsService.insert(materielFlowMaterielDetails);

                //添加物料流转统计信息
                ErpMaterielFlowSummary materielFlowSummary=new ErpMaterielFlowSummary();
                materielFlowSummary.setWarehouseId(goCustomerWarehouse.getId());
                materielFlowSummary.setMaterielId(materielFlowMateriel.getId());
                materielFlowSummary.setWorkSheetId(materielFlow.getMaterielFlowSheetId());
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                materielFlowSummary.setMaterielFlowDate(df.format(new Date()));
                materielFlowSummary.setMaterielStorageNumber(erpMateriels.get(i).getMaterielNumber());
                materielFlowSummary.setMaterielStoragePrice(erpMateriels.get(i).getMaterielStoragePrice());
                materielFlowSummary.setMaterielOutflowNumber(erpMateriels.get(i).getMaterielNumber());
                materielFlowSummary.setMaterielOutflowPrice(erpMateriels.get(i).getMaterielStoragePrice());
                //materielFlowSummary.setIncludingTax();
                materielFlowSummary.setMaterielFlowType(1);
                materielFlowSummary.setMaterielRetained(materielRetained);
                materielFlowSummary.setOutWarehouseRetauned(num);  //数据库里没看见
                materielFlowSummary.setMaterielSource(customer.getCusName());
                materielFlowSummary.setMaterielWhereabouts(goCustomer.getCusName());
                materielFlowSummary.setOutWarehouseId(customerWarehouse.getId());
                flowSummaryService.insert(materielFlowSummary);
            }

            result.setCount(1);
            result.setData(materielFlow);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }



    @RequestMapping("/yiHuangShi")
    public Result<List<MaterIelName>> yiHuangShi(){
    	return materielService.yiHuangShi();
    }

  //获得一晃式第一层接口
    @RequestMapping("/selectTop")
    @ApiOperation("获得一晃式第一层接口")
  	public Result<List<ErpSpecifications>> selectTop(){
  		return materielService.selectTop();
  	}
  	
  	//获得一晃式品牌规格接口
    @RequestMapping("/selectTwo")
    @ApiOperation("获得一晃式品牌规格接口")
  	public Result<List<Map<String, Object>>> selectTwo(String pid){
//        ErpModel pid1 = erpModelService.selectOne(new EntityWrapper<ErpModel>().eq("zid", pid));
//        if (pid1.getName().substring(0,4).equals("乘用轮胎")){
//            pid="SF01543131626169";
//        }

//        pid1.setZid("123");
        return materielService.selectTwo(pid);
  	}
  	
  	//获得一晃式品牌型号接口
    @RequestMapping("/selectThree")
    @ApiOperation("获得一晃式品牌型号接口")
  	public Result<List<Map<String, Object>>> selectThree(String pid){
        ErpSpecifications pid1 = erpSpecificationsService.selectOne(new EntityWrapper<ErpSpecifications>().eq("zid", pid));
        if (pid1!=null){
        if (pid1.getName().substring(0,4).equals("轮胎乘用")){
            pid="SF01543133486928";
        }
        }
//        Result<List<Map<String, Object>>> listResult = materielService.selectThree(pid);

        return materielService.selectThree(pid);
  	}
  	
  	//获得一晃式系统参数接口 69 51 27
    @RequestMapping("/selectSytem")
    @ApiOperation("获得一晃式系统参数接口 69 51 27")
  	public Result<List<String>> selectSytem(int shu){
  		return materielService.selectSytem(shu);
  	}
    
    
  //销售维修 调拨出库 承运企业查询
  @RequestMapping("/selectHuoByCode")
  @ApiOperation("销售维修 调拨出库 承运企业查询")
  @ApiImplicitParam(name = "custId", value = "客户id", required = false, dataType = "int", paramType = "query")
  public Result<List<ErpCustomer>> selectHuoByCode(int custId){
	  return materielFlowService.selectHuoByCode(custId);
  }
  	
  //销售维修 调拨出库 库存物料查询
  @RequestMapping("/selectByWareHouseId")
  @ApiOperation("销售维修 调拨出库 库存物料查询")
  @ApiImplicitParams({
       @ApiImplicitParam(name = "custId", value = "客户id", required = false, dataType = "int", paramType = "query"),
       @ApiImplicitParam(name = "custWareId", value = "客户仓库id", required = false, dataType = "int", paramType = "query")
})
      public Result<List<Map<String, Object>>> selectByWareHouseId(int custId,int custWareId,String so){
      Result<List<Map<String, Object>>> listResult = materielFlowService.selectByWareHouseId(custId, custWareId);
      List<Map<String, Object>> list=new ArrayList<>();
      Result<List<Map<String, Object>>> map=new Result<>();
        if (so!=null){
            for (int i = 0; i < listResult.getData().size(); i++) {
                Map<String, Object> o =  listResult.getData().get(i);
          if (String.valueOf(o.get("materielName")).contains("维修")){
              list.add(o);
                }
            }

                map.setData(list);

        }else {
           map.setData(listResult.getData());
        }

      return map;
  }

  //销售维修 调拨出库添加
  @RequestMapping("/addMaterielFlow")
  @ApiOperation("销售维修 调拨出库添加")
  @ApiImplicitParams({
      /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),*/
       @ApiImplicitParam(name = "mf", value = "ErpMaterielFlow实体类", required = false, dataType = "int", paramType = "query"),
       @ApiImplicitParam(name = "mfmsJson", value = "ErpMaterielFlowMateriel实体类 生产编号用！号分割", required = false, dataType = "String", paramType = "query"),
       @ApiImplicitParam(name = "userId", value = "用户ID", required = false, dataType = "int", paramType = "query"),
       @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "int", paramType = "query")
})
  public Result<Integer> addMaterielFlow(ErpMaterielFlow mf, String mfmsJson,int userId,int custId){
	  return materielFlowService.addMaterielFlow(mf, mfmsJson, userId, custId);
  }
  
  @RequestMapping("/getSheelIdByDate")
  @ApiOperation("调拨出库-根据日期查询单号")
  @ApiImplicitParam(name = "time", value = "日期", required = false, dataType = "String", paramType = "query")
  public String getSheelIdByDate(String time,String type) {
	  return materielFlowService.getSheelIdByDate(time,type);
  }
  
}

